package com.brotherly.mpgp.view;

import java.io.File;
import java.text.DecimalFormat;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.net.Uri;
import android.os.Environment;
import android.util.AttributeSet;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.Button;

import com.brotherly.framework.app.BaseApplication;
import com.brotherly.framework.event.EventService;
import com.brotherly.framework.service.ServiceManager;
import com.brotherly.mpgp.R;
import com.brotherly.util.downloader.DBUtil;
import com.brotherly.util.downloader.DownLoaderUtil;
import com.brotherly.util.downloader.DownloadInfo;

/**
 * 
 * @author robin
 * @date 2013-6-22 下载组建
 */
public class DownLoadButton extends Button implements OnClickListener, OnLongClickListener
{
    public enum DownLoadType
    {
        NOT("not"), DOWNLOAD("download"), WAIT("wait"), PAUSE("pause"), END("end");

        private final String value;

        private DownLoadType(String value)
        {
            this.value = value;
        }
    }

    private String[] texts = new String[]
    {
            "下载", "正在下载", "等待下载", "继续下载", "安装"
    };

    private Paint mProgressPaint;
    private DownLoadType type;
    private int gameref;
    private String name, url;
    private Context context;
    private float fileSize, complete;

    // 新加的
    public static final int STYLE_GAME_DETAIL_DOWNLOAD_BTN = 1;
    public static final int STYLE_DOWNLOAD_NORMAL = 0;
    private int mStyle = STYLE_DOWNLOAD_NORMAL;
    private String mCurrentStateStr = "";
    private Paint mFileSizePaint = new Paint();
    DecimalFormat mFileSizeFomat = new DecimalFormat("0.00");
    private DownLoaderUtil dlUtil;

    public DownLoadButton(Context context)
    {
        super(context);
        this.context = context;
    }

    public DownLoadButton(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        this.context = context;
        this.dlUtil = DownLoaderUtil.getInstence(this.context);
        init();
    }

    public synchronized void setKey(int gameref, String name)
    {
        this.gameref = gameref;
        this.name = name;
        this.url = new StringBuffer(DownLoaderUtil.BASEURL).append("&gameref=").append(gameref).toString();
    }

    public float getFileSize()
    {
        return fileSize;
    }

    public void setFileSize(float fileSize)
    {
        this.fileSize = fileSize;
    }

    public float getComplete()
    {
        return complete;
    }

    public void setComplete(float complete)
    {
        this.complete = complete;
    }

    public synchronized void setDownLoading()
    {
        this.type = DownLoadType.DOWNLOAD;
    }

    public void showProgress()
    {
        setStatusText();
        if (type == DownLoadType.DOWNLOAD && fileSize != 0)
        {
            float f = complete / fileSize * 100;
            DecimalFormat fnum = new DecimalFormat("##0.00");
            String dd = fnum.format(f);
            setText(dd + "%");
        }
        invalidate();
    }

    public String getUrl()
    {
        return url;
    }

    private void init()
    {
        setOnClickListener(this);
        setOnLongClickListener(this);

        type = DownLoadType.NOT;

        mFileSizePaint.setColor(0xFFFFFFFF);
        mFileSizePaint.setTextAlign(Align.LEFT);
        mFileSizePaint.setTextSize(20);
        mFileSizePaint.setAntiAlias(true);

        mProgressPaint = new Paint();
        mProgressPaint.setTextSize(30);
        mProgressPaint.setColor(Color.RED);
        setStatusText();
    }

    public synchronized void setPause()
    {
        this.type = DownLoadType.PAUSE;
        setStatusText();
    }

    @Override
    protected void onDraw(Canvas canvas)
    {
        super.onDraw(canvas);
        int w = getWidth();
        int h = getHeight();

        // if ((this.type == DownLoadType.PAUSE || this.type ==
        // DownLoadType.DOWNLOAD) && this.fileSize != 0)
        if ((this.type == DownLoadType.DOWNLOAD) && this.fileSize != 0)
        {
            mProgressPaint.setAntiAlias(true);
            int progresswidth = w - 18;
            int progressheight = 4;
            int progresstop = h - progressheight - 10;
            int progressleft = 9;
            mProgressPaint.setColor(Color.GRAY);
            mProgressPaint.setStrokeWidth(progressheight);
            canvas.drawRect(progressleft, progresstop, progresswidth + progressleft, progresstop + progressheight,
                    mProgressPaint);
            progressheight = 2;
            progresstop += 1;
            float per = (((float) this.complete) / ((float) this.fileSize));
            if (per > 1)
            {
                per = 0;
            }
            progresswidth = (int) (per * progresswidth);
            mProgressPaint.setColor(0xff0caeb0);
            canvas.drawRect(progressleft, progresstop, progresswidth + progressleft, progresstop + progressheight,
                    mProgressPaint);

        }
        if (mStyle == STYLE_GAME_DETAIL_DOWNLOAD_BTN)
        {
            double fileSize = this.fileSize / 1024.0 / 1024.0;

            String size = mFileSizeFomat.format(fileSize) + "M";
            int sW = (int) mFileSizePaint.measureText(size);
            int sH = (int) (mFileSizePaint.getFontMetrics().bottom - mFileSizePaint.getFontMetrics().top);
            int startX = (int) (w - sW - 10 * getResources().getDisplayMetrics().density);
            int startY = (int) ((h - sH) / 2 - mFileSizePaint.getFontMetrics().ascent);
            canvas.drawText(size, startX, startY, mFileSizePaint);
        }
    }

    public synchronized void stopDownload()
    {
        type = DownLoadType.END;
    }

    public synchronized void pauseDownload()
    {
        this.dlUtil.pauseDownload();
        type = DownLoadType.PAUSE;
    }

    public DownLoadType getType()
    {
        return type;
    }

    public synchronized DownLoadType checkLocalFile()
    {
        String localfile = DownLoaderUtil.APK_PATH + name + ".apk";
        File file = new File(localfile);

        DBUtil dbUtil = DBUtil.getInstance();
        List<DownloadInfo> list = dbUtil.getInfos(this.url);

        if (file.exists())
        {
            for (int i = 0; i < list.size(); i++)
            {
                DownloadInfo info = list.get(i);
                if (info.getComplete() == 1 && info.getUrl().equals(this.url))
                {
                    this.type = DownLoadType.END;
                    setStatusText();
                    return this.type;
                }
                else if (info.getComplete() == 0 && info.getUrl().equals(this.url))
                {
                    if (DownLoaderUtil.getInstence(getContext()).checkCurrentDownLoader(gameref))
                    {
                        this.type = DownLoadType.DOWNLOAD;
                    } else if (DownLoaderUtil.getInstence(getContext()).isDownLoaderWait(url))
                    {
                        this.type = DownLoadType.WAIT;
                    } else
                    {
                        this.type = DownLoadType.PAUSE;
                    }
                    setStatusText();
                    return this.type;
                }
            }
            // 如果文件不在，数据库中就给删除
            file.delete();
            this.type = DownLoadType.NOT;
        }
        else
        {
            if (this.dlUtil.isDownLoaderWait(this.url))
                this.type = DownLoadType.WAIT;
            else
                this.type = DownLoadType.NOT;

        }

        setStatusText();
        return this.type;
    }

    public synchronized void installAPK()
    {
        File file = new File(DownLoaderUtil.APK_PATH + name + ".apk");

        if (!file.exists())
        {
            return;
        }

        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.parse("file://" + file.toString()), "application/vnd.android.package-archive");
        context.startActivity(intent);
        BaseApplication.getInstance().cancelNotify(file.getAbsolutePath());
    }

    public void setStatusText()
    {
        if (mStyle == STYLE_DOWNLOAD_NORMAL)
        {
            switch (this.type)
            {
                case NOT:
                    setText(this.texts[0]);
                    setTextColor(0xFFFFFFFF);
                    // setTextColor(0xffe1802d);
                    // setBackgroundResource(R.drawable.btn_yellow_style);
                    break;
                case DOWNLOAD:
                    setText(this.texts[1]);
                    setTextColor(0xFFFFFFFF);
                    // setTextColor(0xff0caeb0);
                    // setBackgroundResource(R.drawable.btn_blue_style);
                    break;
                case WAIT:
                    setText(this.texts[2]);
                    setTextColor(0xFFFFFFFF);
                    // setTextColor(0xff0caeb0);
                    // setBackgroundResource(R.drawable.btn_blue_style);
                    break;
                case PAUSE:
                    setText(this.texts[3]);
                    setTextColor(0xFFFFFFFF);
                    // setTextColor(0xffc63750);
                    // setBackgroundResource(R.drawable.btn_red_style);
                    break;
                case END:
                    setText(this.texts[4]);
                    setTextColor(0xFFFFFFFF);
                    // setTextColor(0xff7c913f);
                    // setBackgroundResource(R.drawable.btn_green_style);
                    break;
            }
        } else if (mStyle == STYLE_GAME_DETAIL_DOWNLOAD_BTN)
        {
            switch (this.type)
            {
                case NOT:
                    setText("立即" + this.texts[0] + "  ");
                    setTextColor(0xffffffff);
                    break;
                case DOWNLOAD:
                    setText(this.texts[1] + "  ");
                    setTextColor(0xffffffff);
                    break;
                case WAIT:
                    setText(this.texts[2] + "  ");
                    setTextColor(0xffffffff);
                    break;
                case PAUSE:
                    setText(this.texts[3] + "  ");
                    setTextColor(0xffffffff);
                    break;
                case END:
                    setText(this.texts[4] + "  ");
                    setTextColor(0xffffffff);
                    break;
            }
            // setBackgroundResource(R.drawable.game_download_btn_bg);
        }
        if (this.type == DownLoadType.DOWNLOAD && this.fileSize != 0)
        {
            float f = this.complete / this.fileSize * 100;
            if (f > 1)
            {
                f = 0;
            }
            DecimalFormat fnum = new DecimalFormat("##0.00");
            String dd = fnum.format(f);
            this.setText(dd + "%");
        }
        setBackgroundResource(R.drawable.game_download_btn_bg);
    }

    @Override
    public boolean onLongClick(View v)
    {
        if (this.type == DownLoadType.END || this.type == DownLoadType.PAUSE)
        {
            EventService eventService = (EventService) ServiceManager.getInstance().getService(
                    ServiceManager.EVENT_SERVICE);
            eventService.signEvent(DownLoaderUtil.Activity_Event_FileDownload_Info, -2, this);

            return true;
        } else
            return false;
    }

    public synchronized void deleteDownLoadFile()
    {
        if (dlUtil.checkCurrentDownLoader(gameref))// 检查当前下载中的任务，和点击下载的任务是否同一个
        {
            this.dlUtil.pauseDownload();
        }

        File file = new File(DownLoaderUtil.APK_PATH + name + ".apk");
        if (file.isFile())
        {
            file.delete();
            this.type = DownLoadType.NOT;
            setStatusText();

            DBUtil dbUtil = DBUtil.getInstance();
            dbUtil.deleteByUrl(this.url);
        }
    }

    @Override
    public void onClick(View v)
    {
        if (!(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)))
        {
            EventService eventService = (EventService) ServiceManager.getInstance().getService(
                    ServiceManager.EVENT_SERVICE);
            eventService.signEvent(DownLoaderUtil.Activity_Event_FileDownload_Info, -1, 0);
            return;
        }

        if (dlUtil.checkNotDownLoadering()) // 当前没有下载
        {
            if (type == DownLoadType.NOT)
            {
                this.url = DownLoaderUtil.getInstence(context).startDownLoader(gameref, name, 1, (int) fileSize);
                type = DownLoadType.DOWNLOAD;
                setStatusText();
            }
            else if (type == DownLoadType.PAUSE)
            {
                this.url = DownLoaderUtil.getInstence(context).startDownLoader(gameref, name, 1, (int) fileSize);
                type = DownLoadType.DOWNLOAD;
                setStatusText();
            }
            if (type == DownLoadType.END)
            {
                this.installAPK();
            }
        }
        else
        {
            if (dlUtil.checkCurrentDownLoader(gameref))// 检查当前下载中的任务，和点击下载的任务是否同一个
            {
                this.dlUtil.pauseDownload();
                type = DownLoadType.PAUSE;
                setStatusText();
                dlUtil.nextDownload();
            }
            else
            {
                if (type == DownLoadType.END)
                {
                    this.installAPK();
                }
                else if (type == DownLoadType.WAIT)
                {
                    this.dlUtil.cancelWait(gameref);
                    type = DownLoadType.NOT;
                    setStatusText();
                }
                else if (type == DownLoadType.NOT)
                {
                    this.dlUtil.startDownLoader(gameref, name, 1, (int) fileSize);
                    type = DownLoadType.WAIT;
                    setStatusText();
                }
                else if (type == DownLoadType.PAUSE)
                {
                    this.dlUtil.startDownLoader(gameref, name, 1, (int) fileSize);
                    type = DownLoadType.WAIT;
                    setStatusText();
                }
            }
        }
    }

    public void setStyle(int styleGameDetailDownloadBtn)
    {
        this.mStyle = styleGameDetailDownloadBtn;
        setStatusText();
    }
}
